package cn.qingyun.gis.modules.scenes.util;

import cn.qingyun.gis.exception.CommonException;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Slf4j
@Component
public class DbSqlExecutor {
    private static DynamicRoutingDataSource dataSource;
    private static DynamicDataSourceProperties dataSourceProperties;

    /**
     * @param dataSourceName 数据源名称， 例如 scenes_offensive
     * @param executeSql     执行数据库脚本： 例如 create table bak.poi_scenario_la_20241014 as select * from public.poi_scenario_la
     * @return
     */
    @SuppressWarnings("ALL")
    public static void executePreparedStatement(String dataSourceName, String executeSql) {
        log.debug("执行数据库脚本 {}", executeSql);
        try (Connection connection = dataSource.getDataSource(dataSourceName).getConnection();
             PreparedStatement preparedStatement = connection.getMetaData().getConnection().prepareStatement(executeSql)) {
            log.debug("实例化Statement对象...");
            preparedStatement.execute();
        } catch (SQLException e) {
            log.error("执行Sql脚本失败", e);
            throw new CommonException("执行sql脚本失败:" + executeSql + "，异常信息：" + e.getMessage());
        }
    }

    @Resource
    public void setDataSource(DynamicRoutingDataSource dataSource) {
        DbSqlExecutor.dataSource = dataSource;
    }

    @Resource
    public void setDataSourceProperties(DynamicDataSourceProperties dataSourceProperties) {
        DbSqlExecutor.dataSourceProperties = dataSourceProperties;
    }
}
